//
//  TJHttpTool.swift
//  swift网络工具
//
//  Created by TanJian on 15/12/6.
//  Copyright © 2015年 Joshpell. All rights reserved.
//

import UIKit
import AFNetworking

enum TJMethod : String {
    case GET = "GET"
    case POST = "POST"
}

class TJHttpTool: AFHTTPSessionManager {

    // 在 Swift 单例与懒加载格式差不多
    // 把懒加载的 lazy var 改成 static let
    static let shareTool : TJHttpTool = {
        
        let instance = TJHttpTool()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    
    //给回调闭包定义一个别名
    typealias TJNetWorkCallBack = (response:AnyObject?,error:NSError?)->()
    
    
    func request(method:TJMethod , url:String , param:AnyObject? , callback:(response:AnyObject? , error:NSError?) -> ()){
        
        let successCall = { (dataTask:NSURLSessionDataTask , response:AnyObject) -> () in callback(response: response, error: nil)
        }
        
        let failureCall = { (dataTask:NSURLSessionDataTask? , error:NSError) -> () in callback(response: nil, error: error)
        }
        
        if method == .GET{
            self.GET(url, parameters: param, success: successCall, failure: failureCall)
            
        }else{
            
            self.POST(url, parameters: param, success: successCall, failure: failureCall)
            
        }
        
        
    }
    
}


extension TJHttpTool{
    
    func loadAccessToken(code:String,callback:TJNetWorkCallBack) {
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        let param = ["client_id":WB_APPKEY,
            "client_secret":WB_APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_REDIRECTURI]
        
        request(.POST, url: urlStr, param: param,callback: callback)
    }
   
    
    func loadUserInfo(uid:String,accessToken:String,callback:TJNetWorkCallBack) {
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        let param = [
        "uid": uid,
        "access_token": accessToken
        ]
        print("请求数据使用的useracount-----------------------------------------------------\(accessToken)")
        
        request(.GET, url: urlStr, param: param,callback: callback)
     
    }
    
}


extension TJHttpTool {
    
    func loadStatus(accessToken:String,minID:Int64 = 0,maxID:Int64 = 0, callback:TJNetWorkCallBack){
        
        let urlStr = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //请求参数
        let param = [
            "access_token":accessToken,
            "max_id": "\(maxID)",
            "since_id": "\(minID)"
        ]
        request(.GET, url: urlStr, param: param, callback: callback)
    }
}



















